// enhanceApp.js
import postMixin from '@theme/mixins/posts'
import localMixin from '@theme/mixins/locales'
import {
    addLinkToHead
} from '@theme/helpers/utils'
import {
    registerCodeThemeCss
} from '@theme/helpers/other'

import Router from 'vue-router'

const router = new Router({
    mode: 'history'
})

// 防止相同路由跳转时报错
const VueRouterPush = Router.prototype.push
Router.prototype.push = function push (to) {
    return VueRouterPush.call(this, to).catch(err => err)
}

export default ({
    Vue,
    siteData,
    isServer,
    router
}) => {
    Vue.mixin(postMixin)
    Vue.mixin(localMixin)
    if (!isServer) {
        addLinkToHead('//at.alicdn.com/t/font_1030519_2ciwdtb4x65.css')
        registerCodeThemeCss(siteData.themeConfig.codeTheme)
    }

    router.beforeEach((to, from, next) => {
        // 解决非ASCII文件名的路由, 防止 404
        const decodedPath = decodeURIComponent(to.path)
        if (decodedPath !== to.path) {
            next(Object.assign({}, to, {
                fullPath: decodeURIComponent(to.fullPath),
                path: decodedPath
            }))
        } else {
            next()
        }
    })
}
